package com.yang.core.config;

import com.yang.core.api.RestClientInterceptor;
import com.yang.core.model.RequestContext;
import com.yang.core.model.ResponseContext;
import com.yang.core.model.ExceptionContext;
import com.yang.core.config.RestClientProperties.Monitoring;
import lombok.extern.slf4j.Slf4j;

/**
 * RestClient监控拦截器
 */
@Slf4j
public class RestClientMonitoringInterceptor implements RestClientInterceptor {

    private final Monitoring monitoringConfig;

    public RestClientMonitoringInterceptor(Monitoring monitoringConfig) {
        this.monitoringConfig = monitoringConfig;
        log.info("初始化RestClient监控拦截器，日志级别: {}", monitoringConfig.getLogLevel());
    }

    @Override
    public void preRequest(RequestContext context) {
        if (monitoringConfig.isLogRequests()) {
            log.info("发送请求: {} {}", context.getMethod(), context.getUrl());

            if (monitoringConfig.isLogRequestBody() && context.getBody() != null) {
                log.debug("请求体: {}", context.getBody());
            }
        }
    }

    @Override
    public void postResponse(ResponseContext context) {
        if (monitoringConfig.isLogResponses()) {
            log.info("收到响应: {} {} ({}ms)",
                context.getStatusCode(),
                getStatusText(context.getStatusCode()),
                context.getResponseTime());

            if (monitoringConfig.isLogResponseBody() && context.getBody() != null) {
                String body = context.getBody();
                if (body.length() > 200) {
                    log.debug("响应体: {}...", body.substring(0, 200));
                } else {
                    log.debug("响应体: {}", body);
                }
            }
        }
    }

    @Override
    public void onError(ExceptionContext context) {
        if (monitoringConfig.isLogRequests()) {
            log.error("请求失败: {} {} - {}",
                context.getMethod(),
                context.getUrl(),
                context.getException().getMessage());
        }
    }

    /**
     * 获取状态码对应的状态文本
     */
    private String getStatusText(int statusCode) {
        return switch (statusCode) {
            case 200 -> "OK";
            case 201 -> "Created";
            case 202 -> "Accepted";
            case 204 -> "No Content";
            case 400 -> "Bad Request";
            case 401 -> "Unauthorized";
            case 403 -> "Forbidden";
            case 404 -> "Not Found";
            case 500 -> "Internal Server Error";
            default -> "Unknown";
        };
    }
}